import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import ProfileView from '../views/ProfileView.vue'
import AdminLayout from '../layouts/AdminLayout.vue'
import AdminDashboard from '../views/admin/AdminDashboard.vue'
import TeacherVerification from '../views/admin/TeacherVerification.vue'
import AdminSettings from '../views/admin/AdminSettings.vue'
import MenuManagement from '../components/admin/MenuManagement.vue'
import PermissionManagement from '../components/admin/PermissionManagement.vue'

// 动态路由 - 根据用户权限加载
export const dynamicRoutes = [
  {
    path: '/admin/menus',
    name: 'menu-management',
    component: MenuManagement,
    meta: { requiresAuth: true, permission: 'menu:read' }
  },
  {
    path: '/admin/permissions',
    name: 'permission-management',
    component: PermissionManagement,
    meta: { requiresAuth: true, permission: 'permission:read' }
  },
  // 其他动态路由将根据用户权限动态添加
]

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView
  },
  {
    path: '/profile',
    name: 'profile',
    component: ProfileView,
    meta: { requiresAuth: true }
  },
  {
    path: '/admin',
    component: AdminLayout,
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: '',
        name: 'admin-dashboard',
        component: AdminDashboard,
        meta: { requiresAuth: true, requiresAdmin: true }
      },
      {
        path: 'teachers',
        name: 'teacher-verification',
        component: TeacherVerification,
        meta: { requiresAuth: true, requiresAdmin: true }
      },
      {
        path: 'settings',
        name: 'admin-settings',
        component: AdminSettings,
        meta: { requiresAuth: true, requiresAdmin: true }
      }
    ]
  },
  // 动态路由
  ...dynamicRoutes
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// Navigation guard for protected routes
import { useAuthStore } from '@/stores/auth';

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const authStore = useAuthStore();

  // 确保authStore已初始化
  if (token && !authStore.token) {
    authStore.$patch({
      token: token,
      user: JSON.parse(localStorage.getItem('authStore'))?.user || null
    });
  }

  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.meta.requiresAdmin && (!authStore.user || authStore.user.roleId !== 'ADMIN')) {
    // If user is not admin, redirect to home
    next('/')
  } else {
    next()
  }
})

export default router